/*
 * SFTPMessage.cpp
 *
 *  Created on: Mar 14, 2011
 *      Author: sms103
 */

#include "SFTPMessage.h"
#include <stdlib.h>
#include <string.h>

SFTPMessage::SFTPMessage(uint32_t transportMSS) {
	data=NULL;
	setParams(transportMSS);


	messageBuf = malloc(maxMessageSize);
	hdr = (sftp_message_header *)messageBuf;
	data = (char *)messageBuf + sizeof(sftp_message_header);
	currDataBufLen = maxMessageSize - sizeof(sftp_message_header);


	memset(hdr,0,sizeof(sftp_message_header));


}

/* Clears the data for this message
 */
void SFTPMessage::clearData(){
	hdr->dataLength = 0;
}

//adds len bytes from buf to the end of this message's data buffer
//returns bytes added--if the size exceeds maxMessageSize, less than len
//bytes will be added
size_t SFTPMessage::addData(void *buf, size_t len){
	if(len==0)return 0;
	size_t retval = 0;

	retval = currDataBufLen - hdr->dataLength;
	if(retval >= len){
		retval = len;
	}

	memcpy((char *)data + hdr->dataLength, buf, retval);
	hdr->dataLength += retval;
	return retval;

}

/* Sets up to len bytes from buf as the data of this message.
 * returns number of bytes used. Only less than len if len
 * is greater than max amount of data allowed in a msg
 */
size_t SFTPMessage::setData(void *buf, size_t len){
	hdr->dataLength = 0;
	return addData(buf,len);
}

size_t SFTPMessage::setStrData(string s){
	return setData((void *)s.c_str(),s.size()+1);
}

void * SFTPMessage::getData(){
	return data;
}

//sets type field in header to t
void SFTPMessage::setType(uint8_t t){
	hdr->type = t;
}


//sets the attr field in header to attr
void SFTPMessage::setAttr(uint32_t attr){
	hdr->attr = attr;
}



sftp_message_header * SFTPMessage::getHeader(){
	return hdr;
}

void SFTPMessage::toNetByteOrder(){
	hdr->attr = htonl(hdr->attr);
	hdr->dataLength = htonl(hdr->dataLength);
}

void SFTPMessage::toHostByteOrder(){
	hdr->dataLength = ntohl(hdr->dataLength);
	hdr->attr = ntohl(hdr->attr);
}



string& SFTPMessage::getStrData(){
	string *s = new string((char *)data);
	return (*s);
}


uint32_t SFTPMessage::getMaxMessageSize(){
	return maxMessageSize;
}

void SFTPMessage::setParams(uint32_t transportMSS){

	assert(transportMSS);
	maxMessageSize = transportMSS - sizeof(STCPHeader);


}

void * SFTPMessage::mbuf(){
	 return messageBuf;
 }


SFTPMessage::~SFTPMessage() {
	if(messageBuf > 0){
		free(messageBuf);
	}
}
